#!/usr/bin/python
#
# Copyright 2012 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""This code updates the line items read from a text file with their new CPM"""

__authors__ = ['felipel+bulk@google.com (Felipe Lora)', 'gspillmann@google.com (Guillaume Spillmann)']

import os
import sys
import time
from copy import deepcopy

sys.path.insert(0, os.path.join('..', '..', '..', '..'))

# Import appropriate classes from the client library.
from adspygoogle.common import Utils
from adspygoogle.dfp.DfpClient import DfpClient
from adspygoogle.dfp import DfpUtils
from adspygoogle.dfp.DfpErrors import *

# Initialize client object.
client = DfpClient(path=os.path.join('..', '..', '..', '..'))

# Define the currency of CPC, CPM, CPD
CURRENCY = "EUR"

# Initialize appropriate service. By default, the request is always made against
# the production environment.
line_item_service = client.GetLineItemService('https://www.google.com', 'v201111')

# Define names of logs
errorLog = "errors_li_update.log"
successLog = "success_li_update.log"

#############################################################

def getFileLineItems(liFile):
  line_items = []
  lisFile = open(liFile,'rU')

  for line in lisFile.readlines()[1:]:
    line_item = { }
    line = line.replace('\"', '')
    currLine = line.rsplit(",")
    keyword = currLine[8].rsplit("/")
    orderID = keyword[1].rsplit("=")
    filter_statement = {'query': 'WHERE id = \'%s\' and orderId = \'%s\' LIMIT 500' % (keyword[2], orderID[1])}
    response = line_item_service.GetLineItemsByStatement(filter_statement)[0]['results']
    response[0]['costPerUnit'] = currLine[7].rsplit("\n")[0]
    line_items.append(response[0])
  return line_items

def createLIs(lineItems):
  liTemp = deepcopy(lineItems)
  for line_item in liTemp:
    line_item['costPerUnit'] = { 'currencyCode': CURRENCY, 'microAmount': str(int(float(line_item['costPerUnit']) * 1000000)) }
    # A bug is forcing us to read the custom targeting and wrap it in a list
    criteria_list = []
    valueIds_list = []
    if line_item['targeting'].has_key('customTargeting'):
      valueIds_list.append(line_item['targeting']['customTargeting']['children'][0]['children']['valueIds'])
      line_item['targeting']['customTargeting']['children'][0]['children']['valueIds'] = valueIds_list
      criteria_list.append(line_item['targeting']['customTargeting']['children'][0]['children'])
      line_item['targeting']['customTargeting']['children'][0]['children'] = criteria_list
    print '\'%s\' mis a jour avec un taux de %s' %(str(line_item['name']), str(float(line_item['costPerUnit']['microAmount']) / 1000000))

  try: 
    lineItems = line_item_service.UpdateLineItems(liTemp)
    fs = open(successLog,'a')
    for l in lineItems:
      m = "%s, %s\n" % (l['orderId'],l['id'])
      fs.write(m)
    fs.close()
  except DfpRequestError,e:
    errorLogFile = open(errorLog,'a')
    message = "%s\n"  % (e.fault_string)
    errorLogFile.write(message)
    errorLogFile.close()


def Main():
  # Clean old logs
  f = open(errorLog,'w')
  f.write("Order ID, Line item ID,Message\n")
  f.close()
  f = open(successLog,'w')
  f.write("Order ID, Line item ID\n")
  f.close()

  # Read the ad units from the text file
  args = sys.argv[1:]
  liFile = args[0]
  lineItems = getFileLineItems(liFile)
  # Update the line items
  if len(lineItems) != 0:
    print "%s elements de campagne a mettre a jour" % str(len(lineItems))
    createLIs(lineItems)

if __name__ == '__main__':
  Main()

